package com.androider.timememory.activity;

import java.util.ArrayList;
import java.util.HashMap;

import com.androider.timememory.R;
import com.androider.timememory.adapter.ContactsAdapter;
import com.androider.timememory.adapter.ContactsAdapter.ViewHolder;
import com.androider.timememory.db.RecordModel;
import com.androider.timememory.utils.Constants;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

public class AddPeople extends Activity {
	private ArrayList<HashMap<String, Object>> whiteList;
	private ContactsAdapter adapter;
	private Context mContext;
	ListView contactsList;
	Button positive;
	Button negative;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_people_layout);
		mContext = this;
		
		init();
		setOnListeners();
	}
	
	private void init() {
		contactsList = (ListView) findViewById(R.id.contacts_list);
		positive = (Button) findViewById(R.id.positive);
		negative = (Button) findViewById(R.id.negative);
		findViewById(R.id.search).setVisibility(View.GONE);
		
		adapter = new ContactsAdapter(mContext, RecordModel.getContacts(mContext));
		contactsList.setAdapter(adapter);
		whiteList = RecordModel.getWhiteList(mContext);
	}
	
	private void setOnListeners() {
		contactsList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				ViewHolder holder = (ViewHolder) view.getTag();
				holder.cbx.toggle();
				
				adapter.isSelected.put(position, holder.cbx.isChecked());
				
			}
			
		});
		
		positive.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 更新数据列表
				updateWhiteList();
				// 更新数据库
				RecordModel.updateWhiteList(mContext, whiteList);
				// 广播通知白名单更新
				sendBroadcast(new Intent(Constants.ACTION_WHITELIST_UPDATE));
				AddPeople.this.finish();
			}
			
		});
		
		negative.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				AddPeople.this.finish();
			}
			
		});
	}
	
	private void updateWhiteList() {
		ArrayList<HashMap<String, Object>> newList = new ArrayList<HashMap<String, Object>>();
		for(int i = 0; i < adapter.getCount(); i++) {
			if(adapter.isSelected.get(i)) {
				newList.add((HashMap<String, Object>) adapter.getItem(i));
			}
		}
		
		for(HashMap<String, Object> map : newList) {
			if(!whiteList.contains(map)) {
				whiteList.add(map);
			}
			
		}
	}
	
}
